import React, { useEffect, useState } from 'react';
import {
    Card,
    Table,
    Tag,
    Button,
    Space,
    message,
    Tooltip,
    Modal,
    Form,
    Input,
    Select,
    Switch,
} from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, EyeOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import type { ColumnsType } from 'antd/es/table';
import styles from './index.module.css';
import {algorithmApi, AlgorithmConfigVO, AlgorithmQueryParams } from '../../../services/api/algorithm';
import {ALGORITHM_OPTIONS} from "../../../constans/algorithm";

const { confirm } = Modal;
const { Option } = Select;

const AlgorithmListPage: React.FC = () => {
    const navigate = useNavigate();
    const [form] = Form.useForm();
    const [loading, setLoading] = useState(false);
    const [data, setData] = useState<AlgorithmConfigVO[]>([]);
    const [pagination, setPagination] = useState({
        current: 1,
        pageSize: 10,
        total: 0
    });

    // 获取算法列表
    const fetchAlgorithms = async (params: AlgorithmQueryParams = {}) => {
        try {
            setLoading(true);
            const response = await algorithmApi.getAlgorithmList({
                ...params,
                size: params.size || pagination.pageSize // 使用 size 替代 pageSize
            });

            if (response.code === 200 && response.data) {
                setData(response.data.records);
                setPagination({
                    current: response.data.current,
                    pageSize: response.data.size, // 使用返回的 size
                    total: response.data.total
                });
            } else {
                message.error(response.message || '获取数据失败');
            }
        } catch (error) {
            console.error('获取算法列表失败:', error);
            message.error('获取数据失败，请重试');
        } finally {
            setLoading(false);
        }
    };

    // 删除算法配置
    const handleDelete = async (algorithmId: number) => {
        console.log('删除算法配置', algorithmId)
        Modal.confirm({
            title: '确认删除',
            content: '确定要删除这个算法配置吗？该操作不可恢复。',
            okText: '确定',
            okType: 'danger',
            cancelText: '取消',
            onOk: async () => {
                try {
                    const response = await algorithmApi.deleteAlgorithm(algorithmId);
                    if (response.code === 200 && response.data) {
                        message.success('删除成功');
                        // 刷新列表
                        fetchAlgorithms({
                            current: pagination.current,
                            size: pagination.pageSize
                        });
                    } else {
                        message.error(response.message || '删除失败');
                    }
                } catch (error) {
                    console.error('删除算法配置失败:', error);
                    message.error('删除失败，请重试');
                }
            }
        });
    };

    // 查看算法配置详情
    const handleView = async (algorithmId: number) => {
        try {
            const response = await algorithmApi.getAlgorithmDetail(algorithmId);
            if (response.code === 200 && response.data) {
                Modal.info({
                    title: '算法配置详情',
                    width: 600,
                    content: (
                        <div>
                            <p><strong>配置名称：</strong>{response.data.name}</p>
                            <p><strong>算法名称：</strong>{response.data.algorithmName}</p>
                            <p><strong>描述：</strong>{response.data.description}</p>
                            <p><strong>文本处理选项：</strong></p>
                            <ul>
                                <li>区分大小写：{response.data.caseSensitive ? '是' : '否'}</li>
                                <li>忽略空白字符：{response.data.ignoreWhitespace ? '是' : '否'}</li>
                                <li>文本标准化：{response.data.normalizeText ? '是' : '否'}</li>
                            </ul>
                            <p><strong>额外参数：</strong></p>
                            <pre>{JSON.stringify(response.data.additionalParams, null, 2)}</pre>
                            <p><strong>状态：</strong>{response.data.isActive === 1 ? '启用' : '停用'}</p>
                            <p><strong>创建时间：</strong>{new Date(response.data.createdAt).toLocaleString()}</p>
                            <p><strong>更新时间：</strong>{new Date(response.data.updatedAt).toLocaleString()}</p>
                        </div>
                    )
                });
            } else {
                message.error(response.message || '获取详情失败');
            }
        } catch (error) {
            console.error('获取算法配置详情失败:', error);
            message.error('获取详情失败，请重试');
        }
    };

    // 表格列定义
    const columns: ColumnsType<AlgorithmConfigVO> = [
        {
            title: '配置ID',
            dataIndex: 'algorithmId',
            width: 80,
        },
        {
            title: '算法名称',
            dataIndex: 'algorithmName',
            width: 150,
            render: (code: string) => {
                const algorithm = ALGORITHM_OPTIONS.find(a => a.code === code);
                return algorithm ? (
                    <Tooltip title={algorithm.description}>
                        <Tag color="blue">{algorithm.name}</Tag>
                    </Tooltip>
                ) : code;
            }
        },
        {
            title: '配置名称',
            dataIndex: 'name',
            width: 150,
        },
        {
            title: '描述',
            dataIndex: 'description',
            ellipsis: true,
            width: 200,
        },
        {
            title: '文本处理选项',
            width: 200,
            render: (_, record) => (
                <Space>
                    {record.caseSensitive && <Tag>区分大小写</Tag>}
                    {record.ignoreWhitespace && <Tag>忽略空白</Tag>}
                    {record.normalizeText && <Tag>文本标准化</Tag>}
                </Space>
            )
        },
        {
            title: '状态',
            dataIndex: 'isActive',
            width: 100,
            render: (isActive: number) => (
                <Tag color={isActive === 1 ? 'success' : 'default'}>
                    {isActive === 1 ? '启用' : '停用'}
                </Tag>
            )
        },
        {
            title: '创建时间',
            dataIndex: 'createdAt',
            width: 180,
            render: (time: string) => new Date(time).toLocaleString()
        },
        {
            title: '操作',
            width: 180,
            fixed: 'right',
            render: (_, record) => (
                <Space>
                    <Button
                        type="text"
                        icon={<EyeOutlined />}
                        onClick={() => handleView(record.algorithmId)}
                    >
                        查看
                    </Button>
                    <Button
                        type="text"
                        icon={<EditOutlined />}
                        onClick={() => navigate(`/algorithm/edit/${record.algorithmId}`)}
                    >
                        编辑
                    </Button>
                    <Button
                        type="text"
                        danger
                        icon={<DeleteOutlined />}
                        onClick={() => handleDelete(record.algorithmId)}
                    >
                        删除
                    </Button>
                </Space>
            )
        }
    ];

    // 处理搜索
    // 处理搜索
    const handleSearch = async (values: any) => {
        const params = {
            ...values,
            current: 1,
            size: pagination.pageSize // 使用 size
        };
        await fetchAlgorithms(params);
    };


    // 处理重置
    // 处理重置
    const handleReset = () => {
        form.resetFields();
        fetchAlgorithms({
            current: 1,
            size: pagination.pageSize // 使用 size
        });
    };


    useEffect(() => {
        fetchAlgorithms();
    }, []);

    return (
        <div className={styles.container}>
            <Card bordered={false}>
                {/* 搜索表单 */}
                <Form
                    form={form}
                    layout="inline"
                    className={styles.searchForm}
                    onFinish={handleSearch}
                >
                    <Form.Item name="name">
                        <Input placeholder="配置名称" allowClear />
                    </Form.Item>
                    <Form.Item name="algorithmName">
                        <Select placeholder="算法名称" allowClear style={{ width: 200 }}>
                            {ALGORITHM_OPTIONS.map(algorithm => (
                                <Option key={algorithm.code} value={algorithm.code}>
                                    {algorithm.name}
                                </Option>
                            ))}
                        </Select>
                    </Form.Item>
                    <Form.Item name="isActive">
                        <Select placeholder="状态" allowClear style={{ width: 120 }}>
                            <Option value={1}>启用</Option>
                            <Option value={0}>停用</Option>
                        </Select>
                    </Form.Item>
                    <Form.Item>
                        <Space>
                            <Button type="primary" htmlType="submit">
                                搜索
                            </Button>
                            <Button onClick={handleReset}>重置</Button>
                            <Button
                                type="primary"
                                icon={<PlusOutlined />}
                                onClick={() => navigate('/algorithm/add')}
                            >
                                新增配置
                            </Button>
                        </Space>
                    </Form.Item>
                </Form>

                {/* 数据表格 */}
                <Table
                    columns={columns}
                    dataSource={data}
                    rowKey="algorithmId"
                    pagination={{
                        ...pagination,
                        showSizeChanger: true,
                        showQuickJumper: true,
                        showTotal: (total) => `共 ${total} 条数据`
                    }}
                    loading={loading}
                    onChange={(newPagination) => {
                        fetchAlgorithms({
                            current: newPagination.current,
                            size: newPagination.pageSize
                        });
                    }}
                    scroll={{ x: 1300 }}
                />
            </Card>
        </div>
    );
};

export default AlgorithmListPage;
